package com.help.knowhelps.ui;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfigeration;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.MyLocationConfigeration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.help.knowhelps.R;
import com.help.knowhelps.date.Question;
import com.help.knowhelps.ui.MyOrientationListener.OnOrientationListener;

public class MainActivity extends Activity{
	public static final String TAG = "MainActivity";
	/**
	 * 地图控件
	 */
	private MapView map ;
	/**
	 * 地图实例
	 */
	private BaiduMap mBaiduMap;
	/**
	 * 定位的客户端
	 */
	private LocationClient mLocationClient;
	/**
	 * 定位的监听器
	 */
	public MyLocationListener mMyLocationListener;
	/**
	 * 方向传感器的监听器
	 */
	private MyOrientationListener myOrientationListener;
	/**
	 * 当前定位的模式
	 */
	private LocationMode mCurrentMode = LocationMode.NORMAL;
	/***
	 * 是否是第一次定位
	 */
	private volatile boolean isFristLocation = true;
	/**
	 * 方向传感器X方向的值
	 */
	private int mXDirection;
	/**
	 * 当前的精度
	 */
	private float mCurrentAccracy;
	/**
	 * 最新一次的经纬度
	 */
	private double mCurrentLantitude;
	private double mCurrentLongitude;
	/**
	 * 遮罩图标
	 */
	private List<BitmapDescriptor> mIconMakers = new ArrayList<BitmapDescriptor>();
	View ly_answer,ly_nonet, ll_map;
	ImageView iv_head,iv_enter;
	TextView tv_entity;
	private boolean logined = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		SDKInitializer.initialize(getApplicationContext());
		setContentView(R.layout.activity_main);
		initComponent();
	}
	private void initComponent()
	{
		UiUtils.InitActionBar(this, getResources().getString(R.string.app_name), 
				UiUtils.ACTIONBAR_BUTTON_DISAPPEAR, R.drawable.icon_head,clicklistener);
		map = (MapView)findViewById(R.id.main_map);
		map.setOnTouchListener(touchlistener);
		findViewById(R.id.main_imageView_location).setOnClickListener(clicklistener);
		// 初始化问题图标
		mIconMakers.add(BitmapDescriptorFactory.fromResource(R.drawable.icon_red_select));
		mIconMakers.add(BitmapDescriptorFactory.fromResource(R.drawable.icon_yellow_select));
		mIconMakers.add(BitmapDescriptorFactory.fromResource(R.drawable.icon_green_select));
		mIconMakers.add(BitmapDescriptorFactory.fromResource(R.drawable.icon_bule_select));
		ll_map = findViewById(R.id.main_layout_map);
		ly_answer = findViewById(R.id.main_layout_answer);
		ly_nonet = findViewById(R.id.main_layout_nonet);
		
		iv_head = (ImageView) findViewById(R.id.main_layout_imageView_head);
		tv_entity = (TextView) findViewById(R.id.main_layout_textView_entity);
		iv_enter = (ImageView) findViewById(R.id.main_layout_imageView_enter);
		// 获得地图的实例
		mBaiduMap = map.getMap();
		MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
		mBaiduMap.setMapStatus(msu);
		// 初始化定位
		initMyLocation();
		// 初始化传感器
		initOritationListener();
		// 初始化遮罩监听
		initMarkerClickEvent();
		
			// 2秒后获取问题，保证地图加载完毕
			new Timer().schedule(new TimerTask() {
				
				@Override
				public void run() {
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							List<Question> questions = initTestData();
							addQuestionsOverlay(questions);
							
						}
					});
					
					
				}
			}, 3000L);
			
			new Timer().schedule(new TimerTask() {
				
				@Override
				public void run() {
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							center2myLoc();
						}
					});
					
					
				}
			}, 5000L);
	}
	private void UpdateState()
	{
		boolean isConnect =  true;  //是否联网状态  默认false
		boolean hasAnswer = true; //是否有回复  默认false
//		isConnect = ;// do...
//		hasAnswer = ;// do...
		if(isConnect){
			ll_map.setVisibility(View.VISIBLE);
			ly_nonet.setVisibility(View.GONE);
		}else{
			ll_map.setVisibility(View.GONE);
			ly_nonet.setVisibility(View.VISIBLE);
		}
		if(hasAnswer)
		{
			ly_answer.setVisibility(View.VISIBLE);
			// do...
//			iv_head.setImageDrawable(drawable); 
//			tv_entity.setText(text);
			ly_answer.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent it_helpdetail = new Intent(MainActivity.this,OthersHelpDetailActivity.class);
//					it_helpdetail.putExtra(name, value);// do...  传递数据  ,消息用户
					startActivity(it_helpdetail);
//					hasAnswer = fasle; // do.. 记录hasAnswer 状态.
				}
			});
		}else{
			ly_answer.setVisibility(View.GONE);
		}
	}
	/**
	 * 初始化测试问题
	 * @return
	 */
	private List<Question> initTestData() {
		List<Question> questions = new ArrayList<Question>();
		Question q1 = new Question();
		q1.setLatitude(mCurrentLantitude);
		q1.setLongitude(mCurrentLongitude+0.02);
		q1.setContent("现在去望京吃麻辣香锅需要排队吗？");
		String[] pictures = new String[]{"/com/help/knowhelps/assets/head_1.png"};
		q1.setPictures(pictures);
		questions.add(q1);
		
		Question q2 = new Question();
		q2.setLatitude(mCurrentLantitude+0.005);
		q2.setLongitude(mCurrentLongitude);
		q2.setContent("我的金毛今天走失了，求帮忙？");
		String[] pictures2 = new String[]{"/com/help/knowhelps/assets/head_2.png"};
		q2.setPictures(pictures2);
		questions.add(q2);
		
		Question q3 = new Question();
		q3.setLatitude(mCurrentLantitude+0.01);
		q3.setLongitude(mCurrentLongitude-0.01);
		q3.setContent("小伙伴们望京哪里有比较正宗的川菜？");
		String[] pictures3 = new String[]{"/com/help/knowhelps/assets/head_3.png"};
		q3.setPictures(pictures3);
		questions.add(q3);
		
		Question q4 = new Question();
		q4.setLatitude(mCurrentLantitude+0.005);
		q4.setLongitude(mCurrentLongitude-0.01);
		q4.setContent("大悦城有星巴克吗？");
		String[] pictures4 = new String[]{"/com/help/knowhelps/assets/head_4.png"};
		q4.setPictures(pictures4);
		questions.add(q4);
		
		return questions;
		
	}
	
	private OnClickListener clicklistener = new OnClickListener() {
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.actionbar_imageView_right:
//				logined = true; //test
				if(logined)
					startActivity(new Intent(MainActivity.this,UserActivity.class));
				else
					startActivity(new Intent(MainActivity.this,LoginActivity.class));
				break;
			case R.id.main_imageView_location:
				center2myLoc();
				break;
			default:
				break;
			}
		}
	};
	private OnTouchListener touchlistener = new OnTouchListener() {
		public boolean onTouch(View v, MotionEvent event) {
//			ShowInfoDialog();
			return false;
		}
	};
	@SuppressLint("NewApi")
	private void ShowInfoDialog(final Question question)
	{
		final AlertDialog dlg = new AlertDialog.Builder(this).create();
		dlg.setCanceledOnTouchOutside(true);// 点击四周消失
		dlg.show();
		WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
		int width;
		if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) < 13) {
			Display display = getWindowManager().getDefaultDisplay();
			width = display.getWidth();
		} else {
			Display display = getWindowManager().getDefaultDisplay();
			android.graphics.Point size = new android.graphics.Point();
			display.getSize(size);
			width = size.x;
		}
		if (width == 480) {
			params.width = (int) (width * 0.75);
		}
		params.width = (int) (width * 0.9);
		dlg.getWindow().setAttributes(params);
		Window window = dlg.getWindow();
		window.setContentView(R.layout.info_dialog);
		((TextView)window.findViewById(R.id.info_dialog_textView_name)).setText(question.getContent());
//		((ImageView)window.findViewById(R.id.info_dialog_imageview_head)).setImageResource(R.drawable.head_1);
		
		String[] Pictures = question.getPictures();
		if (Pictures.length > 0) {
			InputStream stream = MainActivity.class.getResourceAsStream(Pictures[0]);
			Drawable picture = new BitmapDrawable(stream);
			((ImageView)window.findViewById(R.id.info_dialog_imageview_head)).setImageDrawable(picture);
		}
		
		
		window.findViewById(R.id.info_dialog_textView_btcancel).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dlg.dismiss();
			}
		});
		window.findViewById(R.id.info_dialog_textView_btsure).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
//				helpsCount = ;   // do...   当前用户需求帮助数量
//				if(helpsCount <= 3){   //需求数小于等于3,直接跳转最新需求.
					Intent it_helpdetail = new Intent(MainActivity.this,OthersHelpDetailActivity.class);
//					it_helpdetail.putExtra(name, value);// do...  传递数据
					startActivity(it_helpdetail);
					
//				}else{     //否则,跳转当前所查看用户的用户帮助中心.
//					startActivity(new Intent(MainActivity.this,OtherHelpsCenterActivity.class));
//				}
				dlg.dismiss();
			}
		});
		
		
	}
	
	// 实现地图生命周期管理
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		map.onDestroy();
		map = null;
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		UpdateState();
		map.onResume();
	}

	@Override
	protected void onPause()
	{
		super.onPause();
		map.onPause();
	}
	
	@Override
	protected void onStart()
	{
		// 开启图层定位
		mBaiduMap.setMyLocationEnabled(true);
		if (!mLocationClient.isStarted())
		{
			mLocationClient.start();
		}
		// 开启方向传感器
		myOrientationListener.start();
		super.onStart();
	}

	@Override
	protected void onStop()
	{
		// 关闭图层定位
		mBaiduMap.setMyLocationEnabled(false);
		mLocationClient.stop();

		// 关闭方向传感器
		myOrientationListener.stop();
		super.onStop();
	}
	
	/**
	 * 初始化定位相关代码
	 */
	private void initMyLocation()
	{
		// 定位初始化
		mLocationClient = new LocationClient(this);
		mMyLocationListener = new MyLocationListener();
		mLocationClient.registerLocationListener(mMyLocationListener);
		// 设置定位的相关配置
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1000);
		mLocationClient.setLocOption(option);
	}
	
	/**
	 * 实现实位回调监听
	 */
	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || map == null)
				return;
			// 构造定位数据
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(mXDirection).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mCurrentAccracy = location.getRadius();
			// 设置定位数据
			mBaiduMap.setMyLocationData(locData);
			mCurrentLantitude = location.getLatitude();
			mCurrentLongitude = location.getLongitude();
			
			// 设置自定义图标
			BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
					.fromResource(R.drawable.navi_map_gps_locked);
			MyLocationConfigeration config = new MyLocationConfigeration(
					mCurrentMode, true, mCurrentMarker);
			mBaiduMap.setMyLocationConfigeration(config);
			// 第一次定位时，将地图位置移动到当前位置
			if (isFristLocation)
			{
				isFristLocation = false;
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				mBaiduMap.animateMapStatus(u);
			}
			
		}
		
	}
	
	/**
	 * 地图移动到我的位置,此处可以重新发定位请求，然后定位； 
	 * 直接拿最近一次经纬度，如果长时间没有定位成功，可能会显示效果不好
	 */
	private void center2myLoc()
	{
		Log.d(TAG, "mCurrentLantitude:" + mCurrentLantitude + ",mCurrentLongitude:" + mCurrentLongitude);
		LatLng ll = new LatLng(mCurrentLantitude, mCurrentLongitude);
		MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
		mBaiduMap.animateMapStatus(u);
	}
	
	/**
	 * 初始化方向传感器
	 */
	private void initOritationListener()
	{
		myOrientationListener = new MyOrientationListener(
				getApplicationContext());
		myOrientationListener
				.setOnOrientationListener(new OnOrientationListener()
			{
				@Override
				public void onOrientationChanged(float x)
				{
					mXDirection = (int) x;

					// 构造定位数据
					MyLocationData locData = new MyLocationData.Builder()
							.accuracy(mCurrentAccracy)
							// 此处设置开发者获取到的方向信息，顺时针0-360
							.direction(mXDirection)
							.latitude(mCurrentLantitude)
							.longitude(mCurrentLongitude).build();
					// 设置定位数据
					mBaiduMap.setMyLocationData(locData);
					// 设置自定义图标
					BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
							.fromResource(R.drawable.navi_map_gps_locked);
					MyLocationConfigeration config = new MyLocationConfigeration(
							mCurrentMode, true, mCurrentMarker);
					mBaiduMap.setMyLocationConfigeration(config);

				}
			});
	}
	
	private void addQuestionsOverlay(List<Question> questions) {
		mBaiduMap.clear();
		LatLng latLng = null;
		OverlayOptions overlayOptions = null;
		Marker marker = null;
		int step = mIconMakers.size();
		int index = 1;
		for (Iterator iterator = questions.iterator(); iterator.hasNext();) {
			Question question = (Question) iterator.next();
			// 位置
			latLng = new LatLng(question.getLatitude(), question.getLongitude());
			Log.d(TAG, "Lantitude:" + question.getLatitude() + ",Longitude:" + question.getLongitude());
//			latLng = new LatLng(40.095574, 116.394019);
			int iconindex = index % step;
			index++;
			// 图标
			overlayOptions = new MarkerOptions().position(latLng).icon(mIconMakers.get(iconindex)).zIndex(5);
			marker = (Marker) (mBaiduMap.addOverlay(overlayOptions));
			Bundle bundle = new Bundle();
			bundle.putSerializable("question", question);
			marker.setExtraInfo(bundle);
		}
		
		// 将地图移到到最后一个经纬度位置
		MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(latLng);
		mBaiduMap.setMapStatus(u);
	}
	
	private void initMarkerClickEvent() {
		
		// 对Marker的点击
		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener()
		{

			@Override
			public boolean onMarkerClick(Marker marker) {
				Question question = (Question)marker.getExtraInfo().get("question");
				ShowInfoDialog(question);
				
				return true;
			}
			
		});
	}
}
